package org.jfrog.gradle.plugin.artifactory;

import org.apache.commons.lang3.StringUtils;
import org.gradle.api.Plugin;
import org.gradle.api.initialization.Settings;
import org.gradle.api.logging.Logging;
import org.jfrog.build.api.util.Log;
import org.jfrog.build.extractor.BuildInfoExtractorUtils;
import org.jfrog.build.extractor.clientConfiguration.ArtifactoryClientConfiguration;
import org.jfrog.gradle.plugin.artifactory.utils.GradleClientLogger;

import java.util.Properties;

@SuppressWarnings("unused")
public class ArtifactoryPluginSettings implements Plugin<Settings> {
    private static final Log log = new GradleClientLogger(Logging.getLogger(ArtifactoryPluginSettings.class));

    @Override
    public void apply(Settings settings) {
        ArtifactoryClientConfiguration.ResolverHandler resolver = getResolverHandler();
        if (resolver == null || StringUtils.isAnyBlank(resolver.getContextUrl(), resolver.getRepoKey())) {
            // If there's no configured Artifactory URL or repository, there's no need to include the resolution repository
            return;
        }
        String contextUrl = StringUtils.appendIfMissing(resolver.getContextUrl(), "/");
        settings.getDependencyResolutionManagement().getRepositories().maven(mavenArtifactRepository -> {
            mavenArtifactRepository.setName("artifactoryResolutionRepository");
            mavenArtifactRepository.setUrl(contextUrl + resolver.getRepoKey());

            // Set credentials if provided
            String username = resolver.getUsername();
            String password = resolver.getPassword();
            if (StringUtils.isNoneBlank(username, password)) {
                mavenArtifactRepository.credentials((credentials) -> {
                    credentials.setUsername(username);
                    credentials.setPassword(password);
                });
            }
        });
    }

    /**
     * Extract the resolver information from the build-info.properties file generated by the JFrog CLI or by the
     * Jenkins Artifactory plugin.
     *
     * @return resolver handler.
     */
    private ArtifactoryClientConfiguration.ResolverHandler getResolverHandler() {
        Properties allProps = BuildInfoExtractorUtils.mergePropertiesWithSystemAndPropertyFile(new Properties(), log);
        ArtifactoryClientConfiguration configuration = new ArtifactoryClientConfiguration(log);
        configuration.fillFromProperties(allProps);
        return configuration.resolver;
    }
}
